package com.imooc.course.system.controller.admin;

import com.imooc.course.server.dto.RoleResourceDto;
import com.imooc.course.system.form.RoleResourceForm;
import com.imooc.course.system.form.RoleUserForm;
import com.imooc.course.system.form.PageForm;
import com.imooc.course.server.dto.RoleUserDto;
import com.imooc.course.server.dto.PageDto;
import com.imooc.course.server.dto.ResponseDto;
import com.imooc.course.server.service.RoleUserService;
import com.imooc.course.server.utils.CopyUtil;
import com.imooc.course.server.utils.ValidatorUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;

@RestController
@RequestMapping("/admin/roleUser")
public class RoleUserController {

    private static final Logger log = LoggerFactory.getLogger(RoleUserController.class);
    public static final String BUSINESS_NAME = "角色用户关联";


    @Resource(name = "roleUserService")
    private RoleUserService roleUserService;

    /**
     * 查询列表
     * @param pageForm 传入的page和size
     * @return
     */
    @PostMapping("/list")
    public ResponseDto getList(@RequestBody PageForm pageForm) {
        PageDto pageDto = CopyUtil.copy(pageForm, PageDto.class);
        roleUserService.getList(pageDto);
        return ResponseDto.success().setContent(pageDto);
    }

    /**
     * 保存，id有值为更新，id无值为新增
     * @param roleUserForm
     * @return
     */
    @PostMapping("/save")
    public ResponseDto addRoleUser(@RequestBody RoleUserForm roleUserForm) {
        //入参检查
        ValidatorUtil.notNull(roleUserForm.getRoleId(), "角色");
        ValidatorUtil.notNull(roleUserForm.getUserId(), "用户");

        RoleUserDto roleUserDto = CopyUtil.copy(roleUserForm, RoleUserDto.class);
        roleUserService.save(roleUserDto);
        return ResponseDto.success().setContent(roleUserDto);
    }

    /**
     * 删除
     * @param id
     * @return
     */
    @DeleteMapping("/delete/{id}")
    public ResponseDto del(@PathVariable String id) {
        roleUserService.delete(id);
        return ResponseDto.success();
    }

    /**
     * 用户获取角色授权
     * @param roleUserForm
     * @return
     */
    @PostMapping("/authorization")
    public ResponseDto authorization(@RequestBody RoleUserForm roleUserForm) {
        roleUserService.authorization(CopyUtil.copy(roleUserForm, RoleUserDto.class));
        return ResponseDto.success();
    }

    /**
     * 通过roleId获取关联用户列表
     * @param request
     * @return
     */
    @PostMapping("/user")
    public ResponseDto getAllRoleUser(HttpServletRequest request) {
        String roleId = request.getParameter("roleId");
        List<RoleUserDto> list = roleUserService.getListByRoleId(roleId);
        return ResponseDto.success().setContent(list);
    }
}
